package com.example.service;

import com.example.latch.LeaderLatch;
import com.example.latch.LeaderLatchListener;
import org.redisson.api.RScheduledExecutorService;
import org.redisson.api.RedissonClient;
import org.redisson.api.WorkerOptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class TestServiceImpl implements TestService, InitializingBean, DisposableBean {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private RedissonClient redissonClient;

    private LeaderLatch leaderLatch;

    @Override
    public void afterPropertiesSet() throws Exception {
        this.leaderLatch = new LeaderLatch(redissonClient, "REDIOS_MASTER_KEY", new LeaderLatchListener() {
            @Override
            public void isLeader() {
                logger.warn("master node =============================>>>>>>>");
                RScheduledExecutorService executorService = redissonClient.getExecutorService("myExecutor");
                executorService.registerWorkers(WorkerOptions.defaults());
            }
        });
        this.leaderLatch.start();
    }

    @Override
    public void destroy() throws Exception {
        this.leaderLatch.stop();
    }
}
